import requests
import os
from dotenv import load_dotenv

load_dotenv()

if __name__ == "__main__":
    dir_path = "../data/raw"
    file_name = "shenzhen_geo.json"
    api_key = os.getenv("GAODE_API_KEY")
    url = "https://restapi.amap.com/v3/config/district?key={api_key}&keywords=深圳&subdistrict=3&extensions=all&page={page}"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
        "Accept": "application/json, text/javascript, */*; q=0.01",
    }
    # data_num = 20

    file_path = os.path.join(dir_path, file_name)
    print(f"数据将保存到: {file_path}")
    page = 1
    while True:
        # payload = {
        #     "keywords": "深圳",
        #     "subdistrict": 3,
        #     "page": page,
        #     "offset": data_num,
        #     "extensions": "base",
        # }           
        cur_url = url.format(api_key=api_key, page=page)
        print(cur_url)

        response = requests.request("GET", cur_url, headers=headers, data={})

        print(f"响应结果:{response.status_code}")
        if response.status_code != 200:
            print(f"请求错误，状态码：{response.status_code}")
            break

        with open(file_path, "a", encoding="utf-8") as f:
            f.write(str(response.json()))

        # page += 1
        break

    print(f"获取到{len(response.json()['districts'][0]['districts'])}个区")